import os
import sqlite3
from src.config.database import get_settings, get_database_url, get_initialized_engine

print("=== 数据库连接调试脚本 ===")

# 获取并打印设置信息
settings = get_settings()
print(f"DATABASE_URL (from settings): {settings.DATABASE_URL}")

# 获取并打印通过get_database_url()函数获取的URL
url = get_database_url()
print(f"DATABASE_URL (from get_database_url()): {url}")

# 分析SQLite连接字符串，获取数据库文件路径
if url.startswith('sqlite:///'):
    # 相对路径
    db_path = url[10:]
    absolute_db_path = os.path.abspath(db_path)
    print(f"数据库文件路径 (相对): {db_path}")
    print(f"数据库文件路径 (绝对): {absolute_db_path}")
    
    # 检查文件是否存在
    if os.path.exists(absolute_db_path):
        print(f"✓ 数据库文件存在，大小: {os.path.getsize(absolute_db_path)} bytes")
        
        try:
            # 直接连接到数据库文件，检查users表结构
            conn = sqlite3.connect(absolute_db_path)
            cursor = conn.cursor()
            
            # 检查users表是否存在
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users';")
            table_exists = cursor.fetchone()
            
            if table_exists:
                print("✓ users表存在")
                
                # 检查password_history列是否存在
                cursor.execute("PRAGMA table_info(users);")
                columns = cursor.fetchall()
                column_names = [col[1] for col in columns]
                
                print(f"当前列: {column_names}")
                
                if 'password_history' in column_names:
                    print("✓ password_history列已存在")
                else:
                    print("❌ password_history列不存在")
            else:
                print("❌ users表不存在")
            
            # 关闭连接
            conn.close()
            
        except sqlite3.Error as e:
            print(f"❌ 数据库错误: {e}")
    else:
        print(f"❌ 数据库文件不存在: {absolute_db_path}")
else:
    print("⚠️ 不是SQLite数据库连接字符串")

# 尝试通过SQLAlchemy引擎执行查询，检查实际使用的数据库
print("\n=== 通过SQLAlchemy引擎检查 ===")
try:
    engine = get_initialized_engine()
    print(f"SQLAlchemy引擎创建成功: {engine}")
    
    # 执行一个简单的查询来验证连接
    with engine.connect() as connection:
        result = connection.execute("SELECT 1")
        print(f"✓ SQLAlchemy连接测试成功，结果: {result.scalar()}")
        
        # 检查users表结构
        try:
            # 检查表是否存在
            table_query = """SELECT name FROM sqlite_master WHERE type='table' AND name='users'"""
            table_result = connection.execute(table_query)
            table_exists = table_result.fetchone()
            
            if table_exists:
                print("✓ SQLAlchemy检查: users表存在")
                
                # 检查列信息
                pragma_query = "PRAGMA table_info(users)"
                pragma_result = connection.execute(pragma_query)
                columns = pragma_result.fetchall()
                column_names = [col[1] for col in columns]
                
                print(f"SQLAlchemy检查 - 当前列: {column_names}")
                
                if 'password_history' in column_names:
                    print("✓ SQLAlchemy检查: password_history列已存在")
                else:
                    print("❌ SQLAlchemy检查: password_history列不存在")
                    
                    # 如果列不存在，尝试直接通过SQLAlchemy添加
                    try:
                        print("尝试通过SQLAlchemy添加password_history列...")
                        alter_query = "ALTER TABLE users ADD COLUMN password_history TEXT"
                        connection.execute(alter_query)
                        connection.commit()
                        print("✓ 成功添加password_history列")
                    except Exception as e:
                        print(f"✗ 添加列失败: {e}")
            else:
                print("❌ SQLAlchemy检查: users表不存在")
        except Exception as e:
            print(f"❌ SQLAlchemy查询错误: {e}")
except Exception as e:
    print(f"❌ SQLAlchemy引擎创建失败: {e}")